package org.korosoft.rusalad.syncnrun.cli;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.OptionBuilder;
import org.korosoft.rusalad.syncnrun.Client;
import org.korosoft.rusalad.syncnrun.command.ExecCmd;

import java.io.File;

/**
 * Execute command. Runs a command on remote server.
 *
 * @author Dmitry Korotkov
 * @since 1.0
 */
public class CliExec extends CliClientCommand {
    public CliExec() {
        super("exec", "Executes a file on remote server. Standard output and error streams are forwarded to the client. Exit code is forwarded as well.");
        addCommonLoggingOpts();
        options.addOption(OptionBuilder.withLongOpt("cmd").withDescription("Execute the program").hasArgs(1).hasOptionalArgs().isRequired().create("c"));
        options.addOption(OptionBuilder.withLongOpt("env").withDescription("Environment variables").hasArgs(1).hasOptionalArgs().create());
        options.addOption(OptionBuilder.withLongOpt("workdir").withDescription("Working directory").hasArg().create());
        options.addOption(OptionBuilder.withLongOpt("detach").withDescription("Execute command in a detached console without return code tracking").create());
    }

    @Override
    protected int doExecute(Client client, CommandLine commandLine) throws Exception {
        final String[] cmd = commandLine.getOptionValues("cmd");
        final String[] env = commandLine.getOptionValues("env");
        String workDirName = commandLine.getOptionValue("workdir");
        final File workDir = workDirName == null ? null : new File(workDirName);
        final boolean detach = commandLine.hasOption("detach");
        final ExecCmd.ExecAnswer answer = client.execCommandSynchronously(new ExecCmd(cmd, env, workDir, null, detach));
        return answer.exitCode;
    }
}
